// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PermitAllAndLogAuthorizationService.cs" company="AzureContrib (Open source library http://azurecontrib.codeplex.com)">
//   Microsoft Public License (Ms-PL)
// </copyright>
// <summary>
//   A placeholder access service which lets anything through and logs the access to <see cref="ITrace.Verbose(System.Func{string})" />
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System.Linq;

using AzureContrib.WindowsAzure.Diagnostics;
using AzureContrib.WindowsAzure.Properties;

using Microsoft.IdentityModel.Claims;

namespace AzureContrib.WindowsAzure.AccessControlService
{
	/// <summary>
	/// A placeholder access service which lets anything through and logs the access to <see cref="ITrace.Verbose(System.Func{string})"/>
	/// </summary>
	public class PermitAllAndLogAuthorizationService : IAuthorizationService
	{
		private readonly ITrace trace;

		/// <summary>
		/// Initializes a new instance of the <see cref="PermitAllAndLogAuthorizationService"/> class. 
		/// </summary>
		/// <param name="trace">
		/// The trace.
		/// </param>
		public PermitAllAndLogAuthorizationService(ITrace trace)
		{
			this.trace = trace;
		}

		/// <summary>
		/// Used to <see cref="IAuthorizationService.CheckAccess"/> and grant it to anyone.
		/// </summary>
		/// <param name="context">
		/// The context.
		/// </param>
		/// <returns>
		/// Allways true
		/// </returns>
		public bool CheckAccess(AuthorizationContext context)
		{
			trace.Warning(Strings.PermitAllAndLogAuthorizationServiceAnnouncement.F(GetType()));

			if (trace.VerboseEnabled)
			{
				var authMessage =
					"Authorizing <{0}> to perform <{1}> on <{2}>: Granted!".F(
						string.IsNullOrEmpty(context.Principal.Identity.Name) ? "Anonymous" : context.Principal.Identity.Name,
						string.Join(", ", context.Action.Select(c => "{0} -> {1}".F(c.ClaimType, c.Value))),
						string.Join(", ", context.Resource.Select(c => "{0} -> {1}".F(c.ClaimType, c.Value))));
				trace.Verbose(authMessage);
			}

			return true;
		}
	}
}